<?php

namespace app\modules\common\controllers;

use app\controllers\BaseController;
use app\services\User;
use app\utils\Utils;
use Yii;
use yii\helpers\ArrayHelper;


class SelectController extends BaseController
{
    public function actionUserList($data = 0)
    {
        if (!$data) {
            return $this->render('/select/user/list');
        }

        $request = Yii::$app->request;

        $where[] = ['status' => [10, 20]];

        if ($search = Utils::formUnserialize($request->post('searchData'))) {
            foreach ($search as $k => $v) {
                if ($v === '') {
                    continue;
                }
                switch ($k) {
                    case 'order_no':
                        $where[] = ['id' => Utils::getNumeric($v, 'USER')];
                        break;
                    case 'username':
                    case 'status':
                        $where[] = [$k => $v];
                        break;
                    default:
                        $where[] = ['like', $k, $v];
                        break;
                }
            }
        }

        $result = User::listPage($where, '*', 'id DESC', $request->post('page', 1), $request->post('limit', 10));
        $return = ArrayHelper::toArray($result);

        foreach ($result['data'] as $key => $val) {
            $return['data'][$key]['order_no'] = Utils::generateOrderNo('USER', $val->id);
            $return['data'][$key]['created_at'] = date('Y-m-d H:i:s', $val->created_at);
            $return['data'][$key]['status'] = $val::getStatus()[$val->status];
        }
        return $this->asJson($return);
    }


    public function actionUserView($id)
    {
        if (!$model = User::findOne(['id' => $id, 'status' => [10, 20]])) {
            return $this->alert('未找到该用户');
        }

        return $this->render('/select/user/view', ['model' => $model, 'product_array' => $model->getSelfProductIdArray()]);
    }
}
